var cry = require('crypto');
var uuid = require('node-uuid');
var async = require('async');
var path = require('path');
var fs = require('fs');
var formidable = require("formidable"),
http = require("http"),
util = require("util"),
_ = require("underscore");

module.exports = class extends think.kms.extIndex {
  constructor(ctx) {
    super(ctx);
    this.pdb = this.model('ext_attachment_pic');
    this.fdb = this.model('ext_attachment_file');
  }
  async createUniqueFileName(info) {
    let str = '' + info.userId + info.name + info.type + info.lastModifiedDate + info.size;
    return crypto.createHash('md5').update(str, 'utf8').digest('hex');
  }

  async randomFileName(extname) {
    return uuid.v4() + extname;
  }

  async chunksMarge(dir, targetSteam, total, callback) {
    let index = 0;
    async.whilst(() => {
      return index < total;
    }, function(cb) {
      let originStream = fs.createReadStream(path.join(dir, index.toString()));
      originStream.pipe(targetSteam, { end: false });
      originStream.on('end', () => {
        fs.unlink(path.join(dir, index.toString()), () => {
          if (err) {
            // todo 
            think.logger.error(err);
          }
        });

        index++;
        cb();
      });
    }, err => {
      callback(err);
    });
  }

  async uploadAction() {
    const file = think.extend({}, this.file('file'));
    // console.log(file);
    const filepath = file.path;
    const extname = path.extname(file.name);
    const basename = path.basename(filepath) + extname;
    let res;
    let pic_path;
    // 强势插入七牛
    if (Number(this.config('ext.attachment.type')) === 2) {
      const qiniu = this.extService('qiniu', 'attachment');
      const uppic = await qiniu.uploadpic(filepath, basename);
      // console.log(uppic);
      // { fieldName: 'file',
      //     originalFilename: '2015-07-06_BaiduPlayerNetSetup_100.exe',
      //     path: '/Users/Arterli/Projects/CmsWing/runtime/upload/EPKRrpZvCsSV73J-7kuDiiEY.exe',
      //     headers:
      //     { 'content-disposition': 'form-data; name="file"; filename="2015-07-06_BaiduPlayerNetSetup_100.exe"',
      //         'content-type': 'application/x-msdownload' },
      //     size: 1292280 }
      if (!think.isEmpty(uppic)) {
        data = {
          create_time: new Date().getTime(),
          name: file.name,
          savename: basename,
          mime: file.type,
          size: file.size,
          type: 2,
          sha1: uppic.hash,
          md5: think.md5(basename)
        };
      }
      // return false;
    } else {
      const uploadPath = think.resource + '/upload/picture/' + dateformat('Y-m-d', new Date().getTime());
      think.mkdir(uploadPath);
      if (think.isFile(filepath)) {
        fs.renameSync(filepath, uploadPath + '/' + basename);
      } else {
        console.log('文件不存在！');
      }
      file.path = uploadPath + '/' + basename;
      pic_path = '/upload/picture/' + dateformat('Y-m-d', new Date().getTime()) + '/' + basename;
      if (think.isFile(file.path)) {
        const data = {
          path: pic_path,
          create_time: new Date().getTime(),
          status: 1
        };
        res = await this.model('picture').add(data);
      } else {
        console.log('not exist');
      }
    }

    this.json({
      code: 'SUCCESS',
      data: {
        path: pic_path,
        url: pic_path
      }
    });
    // if (think.isUndefined(fields.status)) { // 分片上传
    //   let upDir = '';
    //   let isChunks = !(think.isUndefined(fields.chunks) || parseInt(fields.chunks) <= 0);
    //   if (isChunks) {
    //     upDir = path.join(think.resource + '/upload/download/' + dateformat('Y-m-d', new Date().getTime()), this.createUniqueFileName(fields));
    //   } else {
    //     upDir = think.resource + '/upload/download/' + dateformat('Y-m-d', new Date().getTime());
    //   }
    //   fs.mkdir(upDir, async (err) => {
    //     if (think.isNull(err) || err.code === 'EEXIST') {
    //       let newFileName = '';
    //       if (isChunks) {
    //         fs.open(upDIr + '.tem', 'w', (err, fd) => {
    //           if (err) {
    //             // todo 
    //             think.logger.error(err);
    //           }
    //           fs.close(fd);
    //         });
    //         newFileName = fields.chunks;
    //       } else {
    //         newFileName = await this.randomFileName(path.extname(fields.name));
            
    //       }
    //       fs.rename(fields.file, path.join(upDir, newFileName), async (err) => {
    //         if (err) {
    //           // todo
    //           think.logger.error(err);
    //           this.json(err)
    //           return;
    //         }
    //         _this.json(`{"status": 1, "path": ${newFileName}}`);
    //       })
    //     } else {
    //       //todo
    //       think.logger.debug(err);
    //       this.json({"status":0})
    //     }
    //   })
    // } else if(fields.status == "md5Check" ) {  //秒传校验
    //   //todo 模拟去数据库中校验md5是否存在
    //   if(fields.md5 == "b0201e4d41b2eeefc7d3d355a44c6f5a"){
    //     res.end('{"ifExist":1, "path":"kazaff2.jpg"}');
    //   }else{
    //       res.end('{"ifExist":0}');
    //   }
    // } else if (fields.status == "chunkCheck") {  //分片校验
    //   fs.stat(path.join(config.uploadDir, fields.name, fields.chunkIndex), function(err, stats){
    //     if(err || stats.size != fields.size){
    //         res.end('{"ifExist":0}');
    //     }else{
    //         res.end('{"ifExist":1}');
    //     }
    //   });
    // } else if (fields.status == "chunksMerge") {   //分片合并
    //   if(_.contains(lockMark, fields.name)){
    //     res.end('{"status":0}');
    //   }else{
    //     lockMark.push(fields.name);
    //     var newFileName = this.randomFileName(fields.ext);
    //     var targetStream = fs.createWriteStream(path.join(config.uploadDir, newFileName));
    //     this.chunksMerge(path.join(config.uploadDir, fields.name), targetStream, fields.chunks, function(err){
    //         if(err){
    //             //todo
    //             console.error(err);
    //             res.end('{"status":0}');
    //             return ;
    //         }
    //         targetStream.end(function(){
    //             //删除文件夹和tmp
    //             fs.unlink(path.join(config.uploadDir, fields.name) + ".tmp", function(err){
    //                 if(err){
    //                     //todo
    //                     console.error(err);
    //                 }
    //             });
    //             fs.rmdir(path.join(config.uploadDir, fields.name), function(err){
    //                 if(err){
    //                     //todo
    //                     console.error(err);
    //                 }
    //             });
    //             lockMark = _.without(lockMark, fields.name);
    //             //todo 这里其实需要把该文件和其前端校验的md5保存在数据库中，供秒传功能检索
    //             res.end('{"status":1, "path":"' + newFileName + '"}');
    //         });
    //     });
    //   }

    // } else if(action != 'options') {
    //   think.logger.error('not options');
    // }
  }

  async upstateAction() {
    const params = this.post();
    think.logger.debug(params)
    const fileMd5 = params.md5;
    const serviceUrl = await this.pdb.find('md5', fileMd5);
    if (!think.isEmpty(serviceUrl)) {
      return this.json({
        code: 'IS_FOUND',
        data: {
          site_url: serviceUrl
        }
      })
    };
    let config = {
      'uptype': params.uptype,
      'file_url': fileMd5 + path.extname(params.file)
    };
    switch(params.uptype) {
      case 'qiniu':
        config.server = '';
        config.token = '';
        break;
      case 'local':
        config.server = '/ext/webupload/index/upload';
        config.token = '';
        break;
      case 'oss':
        let time = Date.now() + 3600;
        policyText = {
          expiration: dateformat('Y-m-d', new Date().getTime()) + 'T' + dateformat('H:i:s', new Date().getTime()) + '.000Z',
          conditions: [['content-length-range', 0, 1048576000]],
        };
        config.policy = '';
        config.server = '';
        config.site_url = '';
        config.signature = '';
        config.OSSAccessKeyId = '';
    }
    this.json({
      code: 'NOT_FOUND',
      data: config
    })
  }
}